import {
  accountLoginRequest,
  requestUserInfoById,
  requestUserMenusByRoleId
} from '../../service/login/login'
import { IAccount } from '../../service/login/types'
import LocalCache from '../../ultills/cache'
import router from '../../router/index'
import { ElMessage } from 'element-plus'
import {
  mapMenusToRoutes,
  mapMenusToPermissions
} from '../../ultills/map-mennus'
const loginModule = {
  namespaced: true,
  state() {
    return {
      token: LocalCache.getCache('token') ?? '',
      userInfo: LocalCache.getCache('userInfo') ?? {},
      UserMenus: LocalCache.getCache('UserMenus') ?? [],
      permissions: []
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      state.token = token
    },
    changeUserInfo(state, userInfo: any) {
      state.userInfo = userInfo
    },
    changeUserMenus(state, UserMenus: any) {
      //这里拿到不同用户的菜单
      state.UserMenus = UserMenus //设置菜单
      // 在这里决定mian有哪些子路由，并设置子路由
      // UserMenus的Type为2的时候才为它设置路由关系
      const routes = mapMenusToRoutes(UserMenus) //所有该角色的子路由
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户按钮权限
      const permissions = mapMenusToPermissions(UserMenus)
      state.permissions = permissions
    }
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      const loginResult = await accountLoginRequest(payload)

      // 获取用户id和token
      const { id, token } = loginResult.data
      LocalCache.setCache('token', token) //本地缓存token
      commit('changeToken', token)

      // 请求用户信息
      const userInfoResult = await requestUserInfoById(id)
      const userInfo = userInfoResult.data

      // 将登录用户信息缓存到vuex和storage中去
      commit('changeUserInfo', userInfo)
      LocalCache.setCache('userInfo', userInfo)

      // 不同用户有不同的菜单和权限
      //获取用户的菜单
      const UserMenusResult = await requestUserMenusByRoleId(userInfo.role.id)
      // 将用户拥有的菜单存储到localstory和vuex中
      commit('changeUserMenus', UserMenusResult.data)
      LocalCache.setCache('UserMenus', UserMenusResult.data)
      ElMessage.success({
        message: '登录成功',
        type: 'success',
        iconClass: 'el-icon-success'
      })
      // 跳转首页
      router.push('/main')
    }
  }
}
export default loginModule
